<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
    <title>Log List</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <style>
      .pagination > .active > a
      /* .pagination > .active > span,
      .pagination > .active > a:hover,
      .pagination > .active > span:hover,
      .pagination > .active > a:focus,
      .pagination > .active > span:focus */
      {
        background-color: #607d8b;
      }
    </style>
</head>
<body>
  <div class="container">
    <div class="section">
      <div class="row">
        <div class="col m8 s12" id="log-range-radio">
        </div>
        <div class="col m4 s6" id="button_panel">
        </div>
      </div>
      <div class="row" id="log-list">
      </div>
      <div class="row center" id="pagination">
      </div>
    </div>
    <div class="modal" id="batch-modal">
      <!--hide model -->
      <div class="modal-content" id="batch-modal-content">
      </div>
      <div class="modal-footer">
          <a href="#" class="modal-close waves-effect waves-green btn-flat"></a>
          <a href="#" class="modal-close waves-effect waves-green btn-flat" id="batch-button-confirm"></a>
      </div>
    </div>
  </div>

<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/js/materialize.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script>
  var texts = N.GetTexts();
  var batchModeEnabled = false;
  const LogDuration = {
    Day: 'last-day',
    Month: 'last-month',
    Year: 'last-year'
  };

  const logsPerPage = 10;

  function disableBatchMode(){
    //load button
    var panel = $('#button_panel');
    var enableButton = $('<a>').addClass('waves-effect waves-light blue-grey lighten-2 btn').attr('id', 'enable_batch_button')
      .attr('onclick', 'enableBatchMode()').append(
        $('<i>').addClass('material-icons left').text('list')
    );
    if (N.IsChinese()){
      enableButton.append('批量处理');
    }else{
      enableButton.append('Batch Mode');
    }
    $('#batch_delete_button').remove();
    $('#disable_batch_button').remove();
    panel.append(enableButton);
    batchModeEnabled = false;
    reloadLogs();
  }

  function enableBatchMode(){
    //load button
    var panel = $('#button_panel');
    var deleteButton = $('<a>').addClass('waves-effect waves-light blue-grey lighten-2 btn').attr('id', 'batch_delete_button').attr('onclick', 'confirmBatchDelete()').append(
      $('<i>').addClass('material-icons left').text('delete')
    );
    var disableButton = $('<a>').addClass('waves-effect waves-light red lighten-2 btn').attr('id', 'disable_batch_button')
      .attr('onclick', 'disableBatchMode()').append(
        $('<i>').addClass('material-icons left').text('done')
    );
    if (N.IsChinese()){
      deleteButton.append('批量删除');
      disableButton.append('完成批量处理');
    }else{
      deleteButton.append('Batch Delete');
      disableButton.append('Exit Batch Mode');
    }
    $('#enable_batch_button').remove();
    panel.append(deleteButton);
    panel.append(disableButton);
    batchModeEnabled = true;
    reloadLogs();
  }

  function outputMessage(message){
    $('#log-list').empty().append(
      $('<div>').addClass('center').append(
        $('<span>').text(message)
      )
    );
  }

  function switchAllLogs(){
    if ($("input[name='all-checkbox']:checkbox").prop('checked')) {
      $("input[name='batch-target']").prop('checked', true);
    }else{
      $("input[name='batch-target']").prop('checked', false);
    }
  }

  function formatDate(date){
    var padding = function(number){
      var result = "" + number;
      for (var offset = (result).length; offset < 2; offset++){
        result = "0" + result;
      }
      return result;
    };

    return date.getFullYear() + '-' + padding(date.getMonth() + 1) + '-' + padding(date.getDate()) + ' ' + padding(date.getHours()) + ':' + padding(date.getMinutes()) + ':' + padding(date.getSeconds());
  }

  function queryLogs(duration, pageOffset){
    var before = new Date();
    var after = new Date(before);
    switch (duration) {
      case LogDuration.Day:
        after.setDate(before.getDate() - 1);
        break;
      case LogDuration.Month:
        after.setMonth(before.getMonth() - 1);
        break;
      case LogDuration.Year:
        after.setFullYear(before.getFullYear() - 1);
        break;
      default:
        M.toast({html: 'invalid duration'});
        return;
    }
    var queryURL = '/logs/?before=' + encodeURIComponent(formatDate(before)) + '&after=' + encodeURIComponent(formatDate(after)) + '&limit=' + logsPerPage;
    if (0 != pageOffset){
      //offset
      queryURL += '&start=' + (pageOffset*logsPerPage);
    }
    $.getJSON(
      queryURL,
      function(result){
        var pagination = $('#pagination').empty();

        if (0 != result['error_code']) {
          outputMessage(result['message']);
          return;
        }
        if (!result['data']){
          outputMessage('no log available');
          $('#log-list').empty();
          return
        }
        var payload = result['data'];
        var logEntris = payload['logs'];
        var totalLogs = payload['total'];
        if (0 == logEntris.length){
          outputMessage('no log available');
          return;
        }
        var logContainer = $('#log-list').empty();
        var titleItem = $('<div>').addClass('col m2 s3');
        var allLabel, timeLabel, contentLabel;
        if (N.IsChinese()){
          allLabel = '全选';
          timeLabel = '时间';
          contentLabel = '内容';
        }else{
          allLabel = 'Select All';
          timeLabel = 'TimeStamp';
          contentLabel = 'Content';
        }

        if (batchModeEnabled){
          var textSpan = $('<span>').text(allLabel);
          titleItem.append(
            $('<label>').append(
              $('<input>').attr('type', 'checkbox').addClass('filled-in')
                .attr('name', 'all-checkbox').attr('onclick', 'switchAllLogs()')
            ).append(textSpan)
          )
        }else{
          titleItem.text(timeLabel);
        }
        logContainer.append(
          $('<div>').addClass('row').append(
            titleItem
          ).append(
            $('<div>').addClass('col m10 s9').text(contentLabel)
          )
        )

        logEntris.forEach((entry) => {
          var entryID = entry['id'];
          var logTime = entry['time'];
          var logContent = entry['content'];
          var titleContent = $('<div>').addClass('col m2 s3');
          if (batchModeEnabled){
            titleContent.append(
              $('<label>').append(
                $('<input>').attr('type', 'checkbox').addClass('filled-in')
                  .attr('name', 'batch-target').val(entryID)
              ).append($('<span>').text(logTime))
            )
          }else{
            titleContent.text(logTime);
          }
          logContainer.append(
            $('<div>').addClass('row').append(
              titleContent
            ).append(
              $('<div>').addClass('col m10 s9').text(logContent)
            )
          )
        });

        //pagination
        if(totalLogs > logsPerPage){
          var pageIndex = 0;
          var pages = $('<ul>').addClass('pagination');
          for (; (pageIndex * logsPerPage) < totalLogs; pageIndex++){
            if (pageIndex == pageOffset){
              //current page
              pages.append(
                $('<li>').addClass('active').append(
                  $('<a>').attr('href', '#').text(pageIndex + 1)
                )
              );
            }else{
              pages.append(
                $('<li>').addClass('waves-effect').append(
                  $('<a>').attr('href', '#').text(pageIndex + 1).attr('onclick', 'loadLogsInPage(' + pageIndex +')')
                )
              );
            }
          }
          pagination.append(pages);
        }
      }
    );
  }


  function confirmBatchDelete(){
    var targets = new Array();
    $("input[name='batch-target']:checkbox:checked").each(function(){
      targets.push($(this).val());
    });
    if (0 === targets.length){
      M.toast({html: 'Must select a log entry'});
      return;
    }
    var targetCount = targets.length;
    var modal = M.Modal.getInstance($('#batch-modal'));
    var content = $('#batch-modal-content').empty().append($('<h4>').text('Batch Delete Log'));
    if(N.IsChinese()){
      content.append(
        $('<div>').text('确认删除这' + targetCount + '条日志吗？')
      );
    }else{
      content.append(
        $('<div>').text('Are you sure to delete ' + targetCount + ' log(s)?')
      );
    }
    $('#batch-button-confirm').attr('onclick', 'batchDeleteLog()');
    modal.open();
  }

  function batchDeleteLog(){
    var targets = new Array();
    $("input[name='batch-target']:checkbox:checked").each(function(){
      targets.push($(this).val());
    });
    if (0 === targets.length){
      M.toast({html: 'Must select a log entry'});
      return;
    }
    var request = new Object();
    request.entries = targets;
    $.ajax({
     url:'/logs/',
     type: "DELETE",
     dataType: "json",
     data:JSON.stringify(request),
     success: function (result) {
         if (0 != result['error_code']) {
             M.toast({html: 'delete log fail: ' + result['message'], outDuration: 1000});
             return;
         }
         M.toast({html: targets.length + ' logs deleted'})
         setTimeout(reloadLogs, 500);
     }
    });
  }

  function reloadLogs(){
    queryLogs($('input[type=radio][name=log-range]:checked').val(), 0);
  }

  function loadLogsInPage(page){
    queryLogs($('input[type=radio][name=log-range]:checked').val(), page);
  }

  function buildRangeOptions(){
    var dayLabel, monthLabel, yearLabel;
    if(N.IsChinese()){
      dayLabel = '最近一天';
      monthLabel = '最近一个月';
      yearLabel = '最近一年';
    }else{
      dayLabel = 'The last day';
      monthLabel = 'The last month';
      yearLabel = 'The last year';
    }
    //initial radio buttons
    var options = $('<div>').addClass('row').append(
      $('<div>').addClass('col m3 s4').append(
        $('<label>').append(
          $('<input>').addClass('with-gap').attr('type', 'radio').attr('name', 'log-range').prop('checked', true).val(LogDuration.Day)
        ).append(
          $('<span>').text(dayLabel)
        )
      )
    ).append(
      $('<div>').addClass('col m3 s4').append(
        $('<label>').append(
          $('<input>').addClass('with-gap').attr('type', 'radio').attr('name', 'log-range').val(LogDuration.Month)
        ).append(
          $('<span>').text(monthLabel)
        )
      )
    ).append(
      $('<div>').addClass('col m3 s4').append(
        $('<label>').append(
          $('<input>').addClass('with-gap').attr('type', 'radio').attr('name', 'log-range').val(LogDuration.Year)
        ).append(
          $('<span>').text(yearLabel)
        )
      )
    );
    $('#log-range-radio').empty().append(options);
    $('input[type=radio][name=log-range]').attr('onchange', 'reloadLogs()');
  }

  $(function(){
    N.ValidateSession();
    buildRangeOptions();

    $('.modal-footer > a:first-child').text(texts.get(N.TagCancel));
    $('.modal-footer > a:last-child').text(texts.get(N.TagConfirm));
    M.AutoInit();
    disableBatchMode();
    reloadLogs();
  });

</script>
</body>
</html>
